package aqsframework.countdownlatch;


import util.MathUtil;

import java.util.concurrent.CountDownLatch;

/**
 * CountDownLatch：倒计时器
 * 就是让主线程等着其他线程的任务结束了再继续执行
 */

public class CountDownLatchExample {

    // 定义一个包含3个计数的CountDownLatch
    private static final int WORKER_THREADS = 4;
    private static final CountDownLatch LATCH = new CountDownLatch(WORKER_THREADS);

    public static void main(String[] args) throws InterruptedException {
        // 创建并启动工作线程
        for (int i = 0; i < WORKER_THREADS; i++) {
            new Thread(() -> {
                System.out.println("工作线程" + Thread.currentThread().getId() + "正在执行任务...");
                // 耗时任务
                MathUtil.resolvePrime();

                System.out.println("工作线程" + Thread.currentThread().getId() + "任务执行完毕！");
                // 当前工作线程完成任务后，CountDownLatch计数减1
                LATCH.countDown();
            }).start();
        }

        // 主线程在此等待，直到所有工作线程都完成任务
        LATCH.await();
        System.out.println("所有工作线程都已完成任务，主线程继续执行...");
    }
}
